package com.ruyuan.seckilling.render.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruyuan.seckilling.common.ChannelKey;
import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.PageRenderResultMessage;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.PageRenderEventHolder;
import com.ruyuan.seckilling.render.config.BussinessConfig;
import com.ruyuan.seckilling.render.entity.PageLog;
import com.ruyuan.seckilling.render.service.PageLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = QueueKey.QUEUE_PUBLISH_PAGE_RESULT, consumerGroup = "publishPageResultGroup")
public class PublishPageResultListener implements RocketMQListener<String> {

    @Autowired
    private PageLogService pageLogService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 消息格式示例
    // .pageLogId(event.getPageLogId())
    // .success(event.isSuccess())
    // .serverIp(BussinessConfig.getMyIp())
    @Override
    public void onMessage(String messageString) {

        log.info("收到页面发布的结果, message={}", messageString);

        JSONObject message = JSONObject.parseObject(messageString);
        Long pageLogId = message.getLong("pageLogId");
        Boolean success = message.getBoolean("success");
        String serverIp = message.getString("serverIp");
        PageLog pageLog = pageLogService.queryById(pageLogId);
        if (!success) {
            log.error("{}发布{}页面失败", serverIp, pageLog.getFileName());
            return;
        }
        String lastestFinshedServerIps;
        String finishedServerIps = pageLog.getFinishedServerIps();
        if (finishedServerIps == null) {
            lastestFinshedServerIps = serverIp;
        } else {
            lastestFinshedServerIps = finishedServerIps + "," + serverIp;
        }
        List<String> list = Arrays.asList(lastestFinshedServerIps.split(","));
        list.sort(Comparator.comparing(e -> e));
        lastestFinshedServerIps = String.join(",", list);
        pageLogService.updataFinishedServerIps(pageLogId, lastestFinshedServerIps);
        log.info("收到页面发布的结果, 修改流水的FinishedServerIps字段");

        if (StringUtils.equals(pageLog.getServerIps(), lastestFinshedServerIps)) {
            String msg = PageRenderResultMessage.builder()
                    .bizData(JSON.parseObject(pageLog.getBizData()))
                    .success(true)
                    .build().toJsonString();
            rocketMQTemplate.convertAndSend(QueueKey.QUEUE_RENDER_PAGE_RESULT, msg);
            log.info("收到页面发布的结果, 检查发现页面已经发布到所有的静态资源服务器上去了，发布页面渲染完成的消息, message={}", msg);
        }
    }
}
